package com.lucy.wx.miniapp.service.impl;

import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.PageResultDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.wx.miniapp.dao.MiniAppGrantDAO;
import com.lucy.wx.miniapp.dao.MiniAppMapDAO;
import com.lucy.wx.miniapp.entity.MiniAppGrant;
import com.lucy.wx.miniapp.entity.MiniAppMap;
import com.lucy.wx.miniapp.service.MiniAppMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class MiniAppMapServiceImpl implements MiniAppMapService {

    @Autowired
    MiniAppMapDAO dao;

    @Override
    public  Optional<MiniAppMap> getAppMap(String appId, String openId) {
        return dao.findByAppIdAndOpenId(appId,openId);
    }

    @Override
    public MiniAppMap getOneUnwrap(Long t) {
        Optional<MiniAppMap> entityOp = dao.findById(t);
        if (!entityOp.isPresent()){
            throw new BusinessException(HttpStatus.NOT_FOUND);
        }
        return entityOp.get();
    }

    @Override
    public PageResultDTO<MiniAppMap> getAll(Pageable pageable, Example<MiniAppMap> example) {
        Page<MiniAppMap> page;

        if (Validator.isEmpty(example)) {
            page = dao.findAll(pageable);
        } else {
            page = dao.findAll(example, pageable);
        }
        /*
          获取分页主体内容
         */
        List<MiniAppMap> list = page.getContent();
        PageResultDTO<MiniAppMap> pageResultDTO = new PageResultDTO<>();


        //封装分页请求结果
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());
        return pageResultDTO;
    }

    @Override
    public List<MiniAppMap> getExample(Example<MiniAppMap> example) {
        return dao.findAll(example);
    }


    @Override
    public void deleteOne(Long id) {
        dao.deleteById(id);
    }

    @Override
    public Optional<MiniAppMap> getOne(Long aLong) {
        return dao.findById(aLong);
    }

    @Override
    public MiniAppMap saveOne(MiniAppMap o) {
        if (Validator.isNotEmpty(o.getId())) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "新建DTO不可携带ID");
        }
        return dao.save(o);
    }

    @Override
    public MiniAppMap updateOne(MiniAppMap o) {
        if (Validator.isEmpty(o.getId())) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "更新DTO必须携带ID");
        }
        return dao.save(o);
    }

}
